﻿// -----------------------------------------------------------------------
// <copyright file="UnityDependencyResolver.cs">
// Copyright (c) 2013 Andrey Veselov. All rights reserved.
// License:  Microsoft Public License (MS-PL)
// Contacts: http://andrey.moveax.com  andrey@moveax.com
// </copyright>
// -----------------------------------------------------------------------

namespace Moveax.DataAccess.Cqrs.Highway.Bootstrappers.Unity
{
    using System.Collections.Generic;
    using System.Diagnostics.Contracts;
    using System.Linq;
    using Microsoft.Practices.Unity;

    internal class UnityDependencyResolver : ICqrsDependencyResolver
    {
        private readonly IUnityContainer _container;

        public UnityDependencyResolver(IUnityContainer container)
        {
            Contract.Requires(container != null);

            this._container = container;
        }

        public T Resolve<T>()
            where T : class
        {
            return this._container.Resolve<T>();
        }

        public T Resolve<T>(IEnumerable<CqrsParameterOverride> ctorParams)
            where T : class
        {
            var unityParams = new ParameterOverrides();
            foreach (var param in ctorParams)
                unityParams.Add(param.Name, param.Value);

            return this._container.Resolve<T>(unityParams);
        }

        public IEnumerable<T> ResolveAll<T>()
            where T : class
        {
            return this._container.ResolveAll<T>();
        }

        public IEnumerable<T> ResolveAll<T>(IEnumerable<CqrsParameterOverride> ctorParams)
            where T : class
        {
            var unityParams = new ParameterOverrides();
            foreach (var param in ctorParams)
                unityParams.Add(param.Name, param.Value);

            var defaultObj = this._container.Resolve<T>(unityParams);
            var namedObjs = this._container.ResolveAll<T>(unityParams);

            return new[] { defaultObj }.Union(namedObjs);
        }
    }
}